package com.xxx.video.mine.activitys;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.utils.ResourcesUtils;
import com.xxx.video.commen.utils.StatusBarUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.utils.SystemActivityUtils;
import com.xxx.video.commen.utils.ToastUtils;
import com.xxx.video.commen.utils.UriUtils;
import com.xxx.video.commen.views.IosSingleChoosePopupWindow;
import com.xxx.video.login.beans.UserInfoBean;
import com.xxx.video.mine.presenters.AccountInformationPresenter;
import com.xxx.video.mine.presenters.IAccountInformationView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class AccountInformationActivity extends BaseActivity<AccountInformationPresenter> implements
        IAccountInformationView, IosSingleChoosePopupWindow.OnIosSingleChooseItemClickListener {
    /**
     * start camera activity request code
     */
    public static final int START_CAMERA_ACTIVITY = 201;
    /**
     * start album activity request code
     */
    public static final int START_ALBUM_ACTIVITY = 202;
    String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    @BindView(R.id.iv_account_information_avatar)
    ImageView ivAccountInformationAvatar;

    @BindView(R.id.tv_account_information_username)
    TextView tvAccountInformationUsername;

    @BindView(R.id.tv_account_information_phone)
    TextView tvAccountInformationPhone;
    @BindView(R.id.tv_account_information_email)
    TextView tvAccountInformationEmail;
    @BindView(R.id.tv_account_information_age)
    TextView tvAccountInformationAge;
    @BindView(R.id.tv_account_information_gender)
    TextView tvAccountInformationGender;
    @BindView(R.id.tv_account_information_nick_name)
    TextView tvAccountInformationNickName;
    /**
     * use camera save image file path
     */
    private String mImageFilePath;
    UserInfoBean.UserBean userBean;

    @Override
    public void initToolbarData() {
        super.initToolbarData();
        showActionBar();
        StatusBarUtil.getInstance().setStatusBarTransparent(this, true);
        setActionBarTitle(R.string.title_account_information_activity);
        setIsShowActionbarLine(true);
    }

    @Override
    protected AccountInformationPresenter createPresenter() {
        return new AccountInformationPresenter(this, this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_account_information;
    }

    @Override
    public void initData(Bundle extras) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPresenter().getUserInfo();
    }

    @OnClick({R.id.cl_account_information_avatar, R.id.cl_account_information_nick_name,
            R.id.cl_account_information_age, R.id.cl_account_information_gender,
            R.id.cl_account_information_phone, R.id.cl_account_information_email})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cl_account_information_avatar:
                showCheckImgDialog();
                break;
            case R.id.cl_account_information_nick_name:
                startChangeNickNameActivity();
                break;
            case R.id.cl_account_information_age:
                showCheckAgeDialog();
                break;
            case R.id.cl_account_information_gender:
                showCheckGenderDialog();
                break;
            case R.id.cl_account_information_phone:
                startChangeMobileActivity();
                break;

            case R.id.cl_account_information_email:
                startChangeEmailActivity();
                break;
            default:
                break;
        }
    }

    private void showCheckAgeDialog() {
        IosSingleChoosePopupWindow iosSingleChooseDialog = new IosSingleChoosePopupWindow(this);
        ArrayList<String> stringArrayList = new ArrayList<>();
        for (int i = 1; i < 200; i++) {
            stringArrayList.add(String.valueOf(i));
        }
        iosSingleChooseDialog.setData("0", StringUtils.getInstance().getString(R.string.dialog_choose_cancel), stringArrayList);
        iosSingleChooseDialog.setOnIosSingleChooseItemClickListener((string, position, type) -> {
            if (type == 2) {
                getPresenter().updateUserInfo("", "", "0");
            } else if (type == 0) {
                getPresenter().updateUserInfo("", "", string);
            }
        });
        iosSingleChooseDialog.showAtLocation(getWindow().getDecorView());
        lightof();
        iosSingleChooseDialog.setOnDismissListener(this::lighton);
    }

    @Override
    public void showCheckGenderDialog() {
        IosSingleChoosePopupWindow iosSingleChooseDialog = new IosSingleChoosePopupWindow(this);
        ArrayList<String> stringArrayList = new ArrayList<>();
        stringArrayList.add(StringUtils.getInstance().getString(R.string.dialog_choose_man));
        iosSingleChooseDialog.setData(StringUtils.getInstance().getString(R.string.dialog_choose_woman), StringUtils.getInstance().getString(R.string.dialog_choose_cancel), stringArrayList);
        iosSingleChooseDialog.setOnIosSingleChooseItemClickListener((string, position, type) -> {
            if (type == 2) {
                getPresenter().updateUserInfo("", "1", "");
            } else if (type == 0) {
                getPresenter().updateUserInfo("", "0", "");
            }
        });
        iosSingleChooseDialog.showAtLocation(getWindow().getDecorView());
        lightof();
        iosSingleChooseDialog.setOnDismissListener(this::lighton);
    }

    @Override
    public void showCheckImgDialog() {
        IosSingleChoosePopupWindow iosSingleChooseDialog = new IosSingleChoosePopupWindow(this);
        ArrayList<String> stringArrayList = new ArrayList<>();
        stringArrayList.add(StringUtils.getInstance().getString(R.string.dialog_choose_album));
        iosSingleChooseDialog.setData(StringUtils.getInstance().getString(R.string.dialog_choose_camera), StringUtils.getInstance().getString(R.string.dialog_choose_cancel), stringArrayList);
        iosSingleChooseDialog.setOnIosSingleChooseItemClickListener(this);
        iosSingleChooseDialog.showAtLocation(getWindow().getDecorView());
        lightof();
        iosSingleChooseDialog.setOnDismissListener(this::lighton);
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @Override
    public void initUserInfoData2View(UserInfoBean successOb) {
        if (successOb == null) {
            return;
        }
        userBean = successOb.user;
        /*
         * avatar
         */
        /*
         * init avatar
         */
        Glide.with(this).load(ResourcesUtils.getInstance().getImagePath(userBean.picUrl))
                .apply(new RequestOptions().circleCrop()
                        .placeholder(R.drawable.icon_default_avatar)
                        .error(R.drawable.icon_default_avatar)
                ).into(ivAccountInformationAvatar);
        /*
         * name
         */
        tvAccountInformationUsername.setText(StringUtils.getInstance().getNotEmptyMsg(userBean.username));
        /*
         * nick name
         */
        tvAccountInformationNickName.setText(StringUtils.getInstance().getNotEmptyMsg(userBean.nickName));

        /*
         * phone
         */
        tvAccountInformationPhone.setText(StringUtils.getInstance().getNotEmptyMsg(userBean.mobile));
        /*
         * email
         */
        tvAccountInformationEmail.setText(StringUtils.getInstance().getNotEmptyMsg(userBean.email));
        /*
         * age
         */
        tvAccountInformationAge.setText(StringUtils.getInstance().getNotEmptyMsg(userBean.age));
        /*
         * gender
         */
        if (TextUtils.equals(userBean.sex, "1")) {
            tvAccountInformationGender.setText(StringUtils.getInstance().getString(R.string.dialog_choose_woman));
        } else {
            tvAccountInformationGender.setText(StringUtils.getInstance().getString(R.string.dialog_choose_man));
        }
    }

    @Override
    public void startChangeMobileActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt("Type", ChangeMobileOrEmailActivity.CHANGE_MOBILE);
        bundle.putString("Content", getMobile());
        intent2Activity(ChangeMobileOrEmailActivity.class, bundle);
    }

    @Override
    public void startChangeEmailActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt("Type", ChangeMobileOrEmailActivity.CHANGE_EMAIL);
        bundle.putString("Content", getEmail());
        intent2Activity(ChangeMobileOrEmailActivity.class, bundle);
    }

    @Override
    public void startChangeNickNameActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt("Type", ChangeMobileOrEmailActivity.CHANGE_NICK_NAME);
        bundle.putString("Content", getNickName());
        intent2Activity(ChangeMobileOrEmailActivity.class, bundle);
    }

    @Override
    public void upDateAvatarInfoSuccess(String avatarUrl) {
        ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_update_avatar_success));
        UserManager.getInstance().putUserAvatar(avatarUrl);
        getPresenter().getUserInfo();
    }

    @Override
    public String getEmail() {
        return tvAccountInformationEmail.getText().toString().trim();
    }

    @Override
    public String getMobile() {
        return tvAccountInformationPhone.getText().toString().trim();
    }

    @Override
    public String getNickName() {
        return tvAccountInformationNickName.getText().toString().trim();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CAMERA_ACTIVITY) {
                //mImageFilePath
                getPresenter().uploadFile(new File(mImageFilePath));
            } else if (requestCode == START_ALBUM_ACTIVITY) {
                if (data != null) {
                    Uri imageUri = data.getData();
                    String imageFilePath = UriUtils.getInstance().getRealPathFromURI(this, imageUri);
                    getPresenter().uploadFile(new File(imageFilePath));
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission is granted. Continue the action or workflow
                    // in your app.
                    SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
                } else {
                    // Explain to the user that the feature is unavailable because
                    // the features requires a permission that the user has denied.
                    // At the same time, respect the user's decision. Don't link to
                    // system settings in an effort to convince the user to change
                    // their decision.
                    ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_camera_permission));
                }
                return;
            default:
                break;
        }
    }

    @Override
    public void onIosSingleChooseItemClick(String string, int position, int type) {
        if (type == 2) {
            /*
             * title click
             */
            mImageFilePath = SystemActivityUtils.getInstance().startCameraActivity(this, START_CAMERA_ACTIVITY);
        } else if (type == 0) {
            /*
             * other item open the album
             */

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // You can use the API that requires the permission.
                SystemActivityUtils.getInstance().startAlbumActivity(this, START_ALBUM_ACTIVITY);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // You can directly ask for the permission.
                    requestPermissions(permissions, 200);
                }
            }
        }
    }
}
